package net.eldeen.stockhack;

import java.util.Date;
import java.util.Timer;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.log4j.Logger;

import net.eldeen.stockhack.service.AsyncDataFetcher;
import net.eldeen.stockhack.service.ForesightWebConnect;
import net.eldeen.stockhack.service.SimpleStockListener;
import net.eldeen.stockhack.service.StockDataFetcher;
import net.eldeen.stockhack.service.WebConnect;


/**
 * Hello world!
 *
 */
public class StockHackApp
{

  private static final Logger LOGGER = Logger.getLogger(StockHackApp.class);

  private Timer updateTimer;
  private CommandLine cliOptions;

  public void setCliOptions(CommandLine cliOptions) {
    this.cliOptions = cliOptions;
  }

  public StockHackApp() {
    updateTimer = new Timer("Update Time");
  }

  /**
   * Setup and wire up all the parts (need spring?)
   */
  private void init() {
    WebConnect webConnect = new ForesightWebConnect("http://www.foresightondemand.com/" + cliOptions.getOptionValue("biz") + "/"
    		, cliOptions.getOptionValue("username"), cliOptions.getOptionValue("password"));

    StockDataFetcher dataFetcher = new StockDataFetcher();
    dataFetcher.setWebConnect(webConnect);

    SimpleStockListener simpleStockListener = new SimpleStockListener();

    AsyncDataFetcher<StockDataFetcher> asyncStockDataFetcher = new AsyncDataFetcher<StockDataFetcher>();
    asyncStockDataFetcher.setDataFetcher(dataFetcher);
    asyncStockDataFetcher.addObserver(simpleStockListener);

    updateTimer.scheduleAtFixedRate(asyncStockDataFetcher, new Date(), 300000);

  }

  private void shutdown() {
    updateTimer.cancel();
  }

  public static void main( String[] args ) {

    StockHackApp hackApp = new StockHackApp();

    Options cliOptions = setupCliOptions();
    try {
      hackApp.setCliOptions(new BasicParser().parse(cliOptions, args));
    }
    catch (ParseException e) {
      new HelpFormatter().printHelp("stockHack.sh", cliOptions, true);
    }

    try {
      hackApp.init();
    } catch (Throwable t) {
      LOGGER.fatal("Exiting...", t);
    } finally {
      hackApp.shutdown();
    }
  }

  private static Options setupCliOptions() {

    Options options = new Options();

    Option username = new Option("u", "username", true, "username to connect to website");

    options.addOption(username);

    Option password = new Option("p", "password", true, "password to connect to website");

    options.addOption(password);
    
    Option biz = new Option("b", "biz", true, "biz site");
    
    options.addOption(biz);

    return options;
  }
}
